package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileUploadService;
import io.minio.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * ClassName: FileUploadServiceImpl
 * Description:
 *
 * @Author 刘艳丽
 * @Create 2024/9/21 8:08
 * @Version 1.0
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    MinioProperties minioProperties;
    @Autowired
    MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) {
        try {
            // 检查桶是否存在
            boolean res = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!res) {
                // 创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());

                String policy = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                        """.formatted(minioProperties.getBucketName());
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policy).build());
            } else {
                System.out.println("exist! ");
            }

            // 原始的文件名字 比如: 1.jpg
            String originalFilename = file.getOriginalFilename();

            // 截取后缀名字
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 拼接新的文件名字
            String fileName = UUID.randomUUID() + suffixName;

            // 上传文件
            minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).contentType(file.getContentType()).stream(file.getInputStream(), file.getSize(), -1).build());
            System.out.println("upload success");

            return String.join("/", minioProperties.getEndpoint(),minioProperties.getBucketName(),fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

